<!-- src/views/business/customer/customer/index.vue -->
<template>
  <div class="customer-management">
    <!-- 操作按钮和搜索框 -->
    <div class="operation-area">
      <div class="operation-buttons">
        <el-button type="primary" @click="openAddCustomerDialog">添加客户</el-button>
        <el-button @click="handleImport">导入</el-button>
      </div>

      <!-- 搜索框 -->
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="请输入公司名称/主营业务"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 客户列表 -->
    <el-table :data="paginatedCustomers" style="width: 100%">
      <el-table-column prop="creditCode" label="统一社会信用代码" />
      <el-table-column prop="companyName" label="公司名称" />
      <el-table-column prop="mainBusiness" label="主营业务" />
      <el-table-column prop="contractAmount" label="合同金额" />
      <el-table-column prop="lastInteractionTime" label="最近业务往来时间">
        <template #default="scope">
          {{ formatDate(scope.row.lastInteractionTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleViewDetails(scope.row)">查看详情</el-button>
          <el-button link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 查看详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="查看详情" width="80%">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="basicInfo">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="统一社会信用代码">{{ currentCustomer.creditCode }}</el-descriptions-item>
            <el-descriptions-item label="公司名称">{{ currentCustomer.companyName }}</el-descriptions-item>
            <el-descriptions-item label="注册资本(万元)">{{ currentCustomer.registerCapital }}</el-descriptions-item>
            <el-descriptions-item label="注册地址">{{ currentCustomer.registerAddress.join('') + currentCustomer.registerDetailAddress }}</el-descriptions-item>
            <el-descriptions-item label="主营业务">{{ currentCustomer.mainBusiness }}</el-descriptions-item>
            <el-descriptions-item label="默认交货地址">{{ currentCustomer.deliveryAddress.join('') + currentCustomer.deliveryDetailAddress }}</el-descriptions-item>
            <el-descriptions-item label="合同金额">{{ currentCustomer.contractAmount }}</el-descriptions-item>
            <el-descriptions-item label="联系人">{{ currentCustomer.contactPerson }}</el-descriptions-item>
            <el-descriptions-item label="联系方式">{{ currentCustomer.contactInfo }}</el-descriptions-item>
            <el-descriptions-item label="添加人">{{ currentCustomer.addedBy }}</el-descriptions-item>
            <el-descriptions-item label="添加时间">{{ formatDate(currentCustomer.addedTime) }}</el-descriptions-item>
            <el-descriptions-item label="最近修改时间">{{ formatDate(currentCustomer.lastModifiedTime) }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="财务信息" name="financialInfo">
          <!-- 财务信息内容 -->
        </el-tab-pane>
        <el-tab-pane label="业务往来信息" name="businessInfo">
          <!-- 业务往来信息内容 -->
        </el-tab-pane>
        <el-tab-pane label="信息变更" name="infoChange">
          <!-- 信息变更内容 -->
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 添加/编辑客户对话框 -->
    <CustomerForm ref="customerFormRef" @customerAdded="handleCustomerAdded" @customerUpdated="handleCustomerUpdated" />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import dayjs from 'dayjs'
import CustomerForm from './CustomerForm.vue'
import { Search } from '@element-plus/icons-vue'

// 模拟数据
const customers = ref([
  {
    id: 1,
    creditCode: '91310106575864243X',
    companyName: '永杰新材料股份有限公司',
    mainBusiness: '从事产品的生产和制造……',
    contractAmount: '100.21万元',
    lastInteractionTime: '2025-03-17 14:37:04',
    registerAddress: ['湖北省', '武汉市', '汉阳区'],
    registerDetailAddress: '汉阳大道123号',
    deliveryAddress: ['湖北省', '武汉市', '武昌区'],
    deliveryDetailAddress: '武昌路456号',
    contactPerson: '张三',
    contactInfo: '13800138000',
    taxpayerType: 'general',
    invoiceType: 'special',
    bankName: '中国银行',
    bankAccount: '1234567890123456',
    billingAddress: ['湖北省', '武汉市', '汉阳区'],
    billingDetailAddress: '汉阳大道123号',
    registerCapital: '100万元',
    addedBy: '李四(lisi)',
    addedTime: '2025-03-20 19:14:12',
    lastModifiedTime: '2025-03-20 19:14:12'
  }
])

// 状态管理
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = 10

// 计算属性
const filteredCustomers = computed(() => {
  return customers.value.filter(customer =>
    customer.companyName.includes(searchQuery.value) ||
    customer.mainBusiness.includes(searchQuery.value)
  )
})

const total = computed(() => filteredCustomers.value.length)

const paginatedCustomers = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  return filteredCustomers.value.slice(start, end)
})

// 添加客户
const handleAdd = () => {
  // 添加客户逻辑
}
// 导入客户信息
const handleImport = async () => {
  // 创建文件选择输入框
  const fileInput = document.createElement('input');
  fileInput.type = 'file';
  fileInput.accept = '.json'; // 只接受JSON文件
  
  fileInput.onchange = async (e) => {
    const file = e.target.files[0];
    if (!file) return;
    
    const formData = new FormData();
    formData.append('file', file);
    
    try {
      const response = await fetch('http://localhost:3000/api/customer/import', {
        method: 'POST',
        body: formData
      });
      
      const result = await response.json();
      
      if (result.success) {
        ElMessage.success(result.message);
        // 如果有导入的数据，更新前端列表
        if (result.data && result.data.length > 0) {
          result.data.forEach(customer => {
            customers.value.unshift(customer);
          });
        }
        // 重置分页到第一页
        currentPage.value = 1;
      } else {
        ElMessage.error(result.message);
      }
    } catch (error) {
      ElMessage.error('导入失败: ' + error.message);
    }
  };
  
  fileInput.click();
};

const handleSearch = () => {
  currentPage.value = 1
}

const formatDate = (dateString) => {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss')
}

// 查看详情
const detailDialogVisible = ref(false)
const activeTab = ref('basicInfo')
const currentCustomer = ref({})

const handleViewDetails = (row) => {
  currentCustomer.value = row
  detailDialogVisible.value = true
}

// 编辑客户
const handleEdit = (row) => {
  customerFormRef.value.openEditDialog(row)
}

const handlePageChange = (newPage) => {
  currentPage.value = newPage
}

const customerFormRef = ref(null)

// 添加客户
const openAddCustomerDialog = () => {
  customerFormRef.value.openDialog()
}

// 处理新增客户
const handleCustomerAdded = (newCustomer) => {
  customers.value.unshift(newCustomer)
  currentPage.value = 1
}

// 处理更新客户
const handleCustomerUpdated = (updatedCustomer) => {
  const index = customers.value.findIndex(customer => customer.id === updatedCustomer.id)
  if (index !== -1) {
    customers.value[index] = updatedCustomer
  }
}
</script>

<style scoped>
.customer-management {
  padding: 20px;
}

.operation-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.operation-buttons {
  white-space: nowrap;
}

.operation-buttons .el-button {
  margin-right: 10px;
}

.search-bar {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>